Creating a Line Chart
This code sample demonstrates how to create a basic line chart using Chart.js with TypeScript. The type definitions provided by @types/chart.js ensure that the configuration object adheres to the expected structure.
const lineChartConfig: Chart.ChartConfiguration = {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
data: [65, 59, 80, 81, 56, 55, 40]
}]
},
options: {
responsive: true
}
};
const ctx = document.getElementById('myChart') as HTMLCanvasElement;
new Chart(ctx, lineChartConfig);
Creating a Bar Chart
This code sample demonstrates how to create a bar chart using Chart.js with TypeScript. The type definitions ensure that the configuration object is correctly structured and provide autocompletion for the properties.
const barChartConfig: Chart.ChartConfiguration = {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
};
const ctx = document.getElementById('myChart') as HTMLCanvasElement;
new Chart(ctx, barChartConfig);
Creating a Pie Chart
This code sample demonstrates how to create a pie chart using Chart.js with TypeScript. The type definitions help ensure that the configuration object is correctly structured and provide autocompletion for the properties.
const pieChartConfig: Chart.ChartConfiguration = {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56'
],
hoverBackgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56'
]
}]
},
options: {
responsive: true
}
};
const ctx = document.getElementById('myChart') as HTMLCanvasElement;
new Chart(ctx, pieChartConfig);